var express = require('express');
const { cityModel, orderCateModel, activityModel, merchantModel, merchantTypeModel, couponModel, orderModel } = require('../module/model');
var router = express.Router();
const alipaySdk = require('./alipay.js')
const AlipayFormData = require('alipay-sdk/lib/form').default
var axios = require('axios')
router.post('/payment',async(req,res)=>{
    //订单号
    let orderId = req.body.orderId;
    //商品总价
    let price = req.body.orderPrice;
    //购买商品的名称
    let name = req.body.name;
    // 开始对接支付宝API
    const formData = new AlipayFormData();
    //调用setMethod 并传入get,会返回可以跳转到支付页面的url,
    formData.setMethod("get");
    // 支付时信息
    const bizContent = {
        out_trade_no: orderId, //订单号
        product_code: "FAST_INSTANT_TRADE_PAY",
        total_amount: price, //总价格
        subject: name, //商品名称
        body: "商品详情", //商品描述
    };
    formData.addField("bizContent", bizContent);
    console.log()
    //支付成功或失败的返回链接（前端页面）
    formData.addField("returnUrl", "http://localhost:5173/order");
  
    // 返回promise
    const result = alipaySdk.exec(
        // "alipay.trade.wep.pay",   --此为唤起手机版支付，测试时显示系统方面有bug所以用的下面这个   ---网页版支付
        "alipay.trade.wap.pay", 
        {},
        { formData: formData }
    ).catch(error => console.error('caught error!', error));
  
    //对接支付宝成功，支付宝返回的数据
    result.then((resp) => {
        res.send({
            data: {
                code: 200,
                success: true,
                msg: "支付中",
                paymentUrl: resp,
            },
        });
    });
  })

                          

router.post('/paymentQuery', async (req, res) => {
    let out_trade_no = req.body.out_trade_no;
    let trade_no = req.body.trade_no;
    // 支付宝配置
    const formData = new AlipayFormData();
    //调用setMethod 并传入get,会返回可以跳转到支付页面的url,
    formData.setMethod("get");
    // 支付时信息
    const bizContent = {
        out_trade_no,
        trade_no
    };
    formData.addField("bizContent", bizContent);

    // 返回promise
    const result = alipaySdk.exec(
        "alipay.trade.query",
        {},
        { formData: formData }
    ).catch(error => console.error('caught error!', error));
    //对接支付宝API
    result.then(resData => {
        console.log(resData);
        axios({
            method: "GET",
            url: resData
        }).then(resdata => {
            let respondeCode = resdata.data.alipay_trade_query_response;
            if (respondeCode.code == 10000) {
                switch (respondeCode.trade_status) {
                    case 'WAIT_BUYER_PAY':
                        res.send({
                            code: 10001,
                            message: "支付宝有交易记录，没付款"
                        })
                        break;
                    case 'TRADE_FINISHED':
                        // 完成交易的逻辑
                        res.send({
                            code: 10002,
                            message: "交易完成(交易结束，不可退款)"
                        })
                        break;
                    case 'TRADE_SUCCESS':
                        // 完成交易的逻辑
                        res.send({
                            code: 10002,
                            message: "交易完成"
                        })
                        break;
                    case 'TRADE_CLOSED':
                        // 交易关闭的逻辑
                        res.send({
                            code: 10003,
                            message: "交易关闭"
                        })
                        break;
                }
            } else if (respondeCode.code == 40004) {
                return res.send({
                    code: 40004,
                    message: "交易不存在"
                })
            }
        }).catch(err => {
            return res.send({
                code: 50000,
                msg: "交易失败",
                data: err
            })
        })
    })
})


router.get('/cityList', async (req, res) => {
    let data = await cityModel.find()
    res.send({
        code: 200,
        data
    })
})

router.post('/citySearch', async (req, res) => {
    const { name } = req.query
    if (!name) {
        return res.json({ code: 400, message: "查询参数缺失" })
    }
    const result = []
    const city = await cityModel.find()
    city.forEach((item) => {
        const matchedCities = item.children.filter(city =>
            city.includes(name)
        )
        if (matchedCities.length > 0) {
            result.push({ index: item.index, children: matchedCities })
            console.log(result)
        }
    })
    return res.json({ code: 200, data: result });
})

router.get('/orderCate', async (req, res) => {
    const data = await orderCateModel.find()
    res.send({
        code: 200,
        data
    })
})

router.get('/activity', async (req, res) => {
    const data = await activityModel.find()
    res.send({
        code: 200,
        data
    })
})

router.get('/getMerchant', async (req, res) => {
    const { page = 1, limit = 5 } = req.query; // 从查询参数中获取页码和限制数量  
    const pageNumber = parseInt(page); // 将页码转换为整数  
    const limitNumber = parseInt(limit); // 将限制数量转换为整数  

    try {
        // 根据页码计算需要跳过的文档数量  
        const skip = (pageNumber - 1) * limitNumber;

        // 使用分页获取商户数据  
        const merchants = await merchantModel.find()
            .skip(skip) // 跳过前面 skip 个文档  
            .limit(limitNumber) // 限制返回数量为 limitNumber  
            .populate('type'); // 填充与商户类型的关联数据  

        // 获取商户总数量，以便前端使用  
        const totalCount = await merchantModel.countDocuments();

        // 创建一个新的数组来保存商户和它们对应的优惠券  
        const data = await Promise.all(merchants.map(async (merchant) => {
            // 查询与当前商户相关的优惠券  
            const coupons = await couponModel.find({ type: merchant._id }); // 获取与当前商户 ID 匹配的优惠券  
            return {
                ...merchant._doc, // 使用商户的原始数据  
                coupons, // 添加优惠券数据  
            };
        }));

        // 返回响应数据  
        console.log(data)
        res.send({
            code: 200, // 响应代码  
            data, // 返回的带有优惠券的商户数据  
            totalCount, // 可选，包含文档的总数量  
        });
    } catch (error) {
        // 捕获错误并返回500状态码  
        res.status(500).send({
            code: 500, // 响应代码  
            message: '内部服务器错误', // 错误信息  
            error: error.message, // 错误详情  
        });
    }
});
router.get('/getMerchantType', async (req, res) => {
    const data = await merchantTypeModel.find()
    console.log(data)
    res.send({
        code: 200,
        data
    })
})

router.get('/getshopDetail', async (req, res) => {
    const _id = req.query._id
    const merchants = await merchantModel.find({ "_id": _id })
    const data = await Promise.all(merchants.map(async (merchant) => {
        // 查询与当前商户相关的优惠券  
        const coupons = await couponModel.find({ type: merchant._id }); // 获取与当前商户 ID 匹配的优惠券  
        return {
            ...merchant._doc, // 使用商户的原始数据  
            coupons, // 添加优惠券数据  
        };
    }));
    console.log(data)
    res.send({
        code: 200,
        data
    })
})

router.get('/getCouponDetail', async (req, res) => {
    const _id = req.query._id
    const data = await couponModel.find({ "_id": _id }).populate({ path: 'type', populate: { path: 'type' } })
    res.send({
        code: 200,
        data
    })
})

router.post('/addOrder', async (req, res) => {
    console.log(req.body)
    await orderModel.create(req.body)
    res.send({
        code: 200
    })
})

router.get('/getOrder', async (req, res) => {  
    try {  
        const cid = req.query.c_id;  
        let data;  

        if (cid) {  // 如果提供了 c_id  
            data = await orderModel.find({ "c_id": cid });  
        } else {  // 如果没有提供 c_id，返回所有订单  
            data = await orderModel.find();  
        }  

        res.send({  
            code: 200,  
            data  
        });  
    } catch (error) {  
        console.error("获取订单时出现错误:", error);  
        res.status(500).send({  
            code: 500,  
            message: "服务器内部错误",  
        });  
    }  
});


router.post('/updateCate', async(req,res)=>{
    console.log(req.body.orderId)
    let orderId = req.body.orderId
    const o_id = {
        c_id:'676cb0b2aa1927093f1d957f'
    }
    await orderModel.updateOne({"orderId":orderId},{$set:o_id})
    res.send({
        code:200
    })

})




module.exports = router;
